﻿Public Class CSVDao
    Public Shared IMPORT_TYPE1 As Integer = 0 '①　最初エラーまで取込,
    Public Shared IMPORT_TYPE2 As Integer = 1 '全てエラー無視
    Public Shared IMPORT_TYPE3 As Integer = 2 '全行正常のみ取込
    Public Shared IMPORT_TYPE4 As Integer = 3 '④　エラー無視の確認
    'CSV出力
    Public Function exportM_USER(ByVal filePath As String) As Boolean
        Dim ret = True
        Try
            Dim dac = New M_UserDao
            Dim data = dac.getM_User
            Dim sr As System.IO.StreamWriter
            Dim enc As System.Text.Encoding = System.Text.Encoding.GetEncoding("Shift_JIS")
            sr = New System.IO.StreamWriter(filePath, False, enc)
            sr.Write("ユーザID")
            sr.Write(","c)
            sr.Write("パスワード")
            sr.Write(","c)
            sr.Write("ユーザ名")
            sr.Write(","c)
            sr.Write("利用者タイプ")
            sr.Write(","c)
            sr.Write("作成者ID")
            sr.Write(","c)
            sr.Write("作成日")
            sr.Write(","c)
            sr.Write("更新者ID")
            sr.Write(","c)
            sr.Write("更新日")
            sr.Write(Environment.NewLine)
            For i = 0 To data.Rows.Count - 1
                sr.Write(ControlChars.Quote & data.Rows(i).Item("USERID").ToString & ControlChars.Quote)
                sr.Write(","c)
                sr.Write(ControlChars.Quote & data.Rows(i).Item("PASSWORD").ToString & ControlChars.Quote)
                sr.Write(","c)
                sr.Write(ControlChars.Quote & data.Rows(i).Item("EMPLOYEENAME").ToString & ControlChars.Quote)
                sr.Write(","c)
                sr.Write(ControlChars.Quote & data.Rows(i).Item("USERTYPE").ToString & ControlChars.Quote)
                sr.Write(","c)
                sr.Write(ControlChars.Quote & data.Rows(i).Item("CREATEUSERID").ToString & ControlChars.Quote)
                sr.Write(","c)
                sr.Write(ControlChars.Quote & data.Rows(i).Item("CREATEDAY").ToString & ControlChars.Quote)
                sr.Write(","c)
                sr.Write(ControlChars.Quote & data.Rows(i).Item("UPDATEUSERID").ToString & ControlChars.Quote)
                sr.Write(","c)
                sr.Write(ControlChars.Quote & data.Rows(i).Item("UPDATEDAY").ToString & ControlChars.Quote)
                sr.Write(Environment.NewLine)
            Next i
            sr.Close()
        Catch ex As Exception
            ret = False
        End Try
        Return ret
    End Function
    'CSV読込
    Public Function readCSV(ByVal filePath As String, ByVal importType As Integer) As CSVDao.ImportResult
        Dim errorsMsg As New System.Text.StringBuilder
        Dim logMsg As New System.Text.StringBuilder
        Dim resultInfo = New CSVDao.ImportResult
        Dim csvData = New DataTable
        Try
            'CSV読込オブジェクトを用意
            Dim csvReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(filePath, System.Text.Encoding.GetEncoding("Shift_JIS"))
            csvReader.TextFieldType = FileIO.FieldType.Delimited
            csvReader.SetDelimiters(",")
            '読込結果情報を持つ
            logMsg.AppendLine("・ファイ名：" & filePath)
            'CSVデータを持つオブジェクトを用意
            csvData.Columns.Add("ユーザID", GetType(String))
            csvData.Columns.Add("パスワード", GetType(String))
            csvData.Columns.Add("ユーザ名", GetType(String))
            csvData.Columns.Add("利用者タイプ", GetType(String))
            '読込を実行
            While Not csvReader.EndOfData
                resultInfo.totalCnt += 1
                errorsMsg.Append("＃" & resultInfo.totalCnt & "行目：")
                Dim errFlg As Boolean = False
                Dim errStr = ""
                Dim currRow As String() = csvReader.ReadFields
                '項目数チェック
                If Not Me.isValidColNumTail(currRow, 4) Then
                    errFlg = True
                    errorsMsg.Append(My.Resources.E_CSV_COLNUM_INVALID)
                    errorsMsg.Append(System.Environment.NewLine)
                Else
                    '項目データチェック
                    Dim userInfo = New User
                    userInfo.userID = currRow(0)
                    userInfo.password = currRow(1)
                    userInfo.repassword = currRow(1)
                    userInfo.userName = currRow(2)
                    userInfo.userType = User.toUserTypeCode(currRow(3))
                    errStr = userInfo.validate(True)
                    If Not errStr.Equals("") Then
                        errFlg = True
                        errorsMsg.Append(errStr)
                        errorsMsg.Append(System.Environment.NewLine)
                    Else
                        'データベース重複チェック
                        Dim dao = New M_UserDao
                        errStr = dao.checkExistedUser(userInfo.userID)
                        If Not errStr.Equals("") Then
                            errFlg = True
                            errorsMsg.Append(errStr)
                            errorsMsg.Append(System.Environment.NewLine)
                        Else
                            'CSV重複チェック
                            If isExistedUserID(csvData, userInfo.userID) Then
                                errFlg = True
                                errorsMsg.Append(MessageCommon.getMessage(userInfo.userID, My.Resources.E_CSV_USERID_DUPLICATED))
                                errorsMsg.Append(System.Environment.NewLine)
                            End If
                        End If
                    End If
                End If
                'エラー判定
                If errFlg = False Then 'エラー無し
                    csvData.Rows.Add(currRow(0), currRow(1), currRow(2), User.toUserTypeCode(currRow(3)))
                    resultInfo.validCnt += 1
                    errorsMsg.Append(My.Resources.I_CSV_ROW_DATA_VALID)
                    errorsMsg.Append(System.Environment.NewLine)
                Else 'エラーあり、CSVチェック種類により処理
                    resultInfo.invalidCnt += 1
                    Select Case importType
                        Case IMPORT_TYPE1 '①　最初エラーまで取込,
                            resultInfo.csvName = filePath
                            resultInfo.csvData = csvData
                            resultInfo.messages = errorsMsg.ToString
                            Exit While
                        Case IMPORT_TYPE2 '②　エラー無視
                            '読込を続ける
                        Case IMPORT_TYPE3 '③　全行正常のみ取込
                            resultInfo.allowFlg = False
                            resultInfo.csvName = filePath
                            resultInfo.csvData = csvData
                            resultInfo.messages = errorsMsg.ToString
                            Exit While
                        Case IMPORT_TYPE4 '④　エラー無視の確認
                            If resultInfo.invalidCnt = 1 Then '最初のエラーしか確認メッセージボックス表示しない
                                If Not MessageCommon.showConfirm(My.Resources.C_CSV_IMPORT_CONFIRM) = DialogResult.OK Then
                                    resultInfo.allowFlg = False
                                    resultInfo.csvName = filePath
                                    resultInfo.csvData = csvData
                                    resultInfo.messages = errorsMsg.ToString
                                    Exit While
                                Else

                                End If
                            End If
                    End Select
                    errorsMsg.AppendLine("")
                End If
            End While

        Catch ex As Exception
            Debug.Write(ex.ToString)
        Finally
        End Try
        resultInfo.csvName = filePath
        resultInfo.csvData = csvData
        resultInfo.messages = errorsMsg.ToString
        Return resultInfo
    End Function
    'DB登録
    Public Sub importM_USER(ByRef resultInfo As CSVDao.ImportResult)
        If resultInfo.allowFlg = True Then
            Dim csvData As DataTable = resultInfo.csvData
            Dim dac = New M_UserDao
            Dim importedData = New DataTable
            Dim importedCnt = 0
            Dim handleCnt = 0
            importedData.Columns.Add("ユーザID", GetType(String))
            importedData.Columns.Add("パスワード", GetType(String))
            importedData.Columns.Add("ユーザ名", GetType(String))
            importedData.Columns.Add("利用者タイプ", GetType(String))
            For Each row As DataRow In csvData.Rows
                handleCnt += 1
                Dim userInfo = New User
                userInfo.userID = row("ユーザID").ToString
                userInfo.password = row("パスワード").ToString
                userInfo.userName = row("ユーザ名").ToString
                userInfo.userType = row("利用者タイプ").ToString
                Dim retMsg = dac.insertUser(userInfo, My.Settings.CurrentUserID)
                If retMsg.Equals("") Then '登録成功
                    importedCnt += 1
                    importedData.Rows.Add(userInfo.userID, userInfo.password, userInfo.userName, userInfo.getUserTypeName)
                End If
            Next
            resultInfo.importedCnt = importedCnt
            resultInfo.importedData = importedData
        End If
    End Sub
    'CSV取込結果コンテナクラス
    Public Class ImportResult
        Public allowFlg As Boolean = True 'DB登録するかどうか判定フラグ
        Public validCnt As Integer = 0
        Public invalidCnt As Integer = 0
        Public importedCnt As Integer = 0
        Public totalCnt As Integer = 0
        Public importTypeName As String = ""
        Public csvName As String = ""
        Public csvData As DataTable = New DataTable
        Public importedData As DataTable = New DataTable
        Public messages As String = ""

        Public Function getInfo() As String
            Dim info = New System.Text.StringBuilder
            info.Append("＊対象CSVファイル：" & csvName)
            info.Append("＊取込方法：" & importTypeName)
            info.Append("＊読込件数：" & totalCnt)
            info.AppendLine("＊登録済件数：" & importedCnt)
            info.AppendLine("＊処理過程：")
            info.AppendLine(messages)
            Return info.ToString
        End Function
    End Class
    'CSV取込データでユーザID重複チェック
    Private Function isExistedUserID(ByVal csvData As DataTable, ByVal userID As String) As Boolean
        For Each row As DataRow In csvData.Rows
            If userID.Equals(row("ユーザID")) Then
                Return True
            End If
        Next
        Return False
    End Function
    '行の項目数チェック
    Private Function isValidColNumTail(ByVal row As String(), ByVal colNum As Integer) As Boolean
        For i = colNum To row.Length - 1
            If Not String.IsNullOrEmpty(row(i)) Then
                Return False
            End If
        Next
        Return True
    End Function
End Class